<?php

namespace Frieza\Modules\Position\Controllers;

use Biz\service\advertisement\apiModule\BaseModule;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Doraemon\model\Position\PositionBaseInfo;
use Doraemon\model\Position\PositionExtend;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\service\position\PositionConstInterface;
use Doraemon\service\position\PositionModule;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;

class SingleBannerController extends BaseController
{
    use BaseTrait;

    public function saveModule(Request $request, $baseInfoId)
    {
        $base = $request->input('base', []);
        $rules = $request->input('rules', []);
        $pic = $base['pic_id'] ?? '';
        switch ($this->positionId) {
            case PositionConstInterface::HOME_ROOF:
            case PositionModule::HOME_TODAY_ARTICLE:
            case PositionModule::HOME_CAROUSEL_V5:
            case PositionModule::HOME_RECOMMEND_GREET_BANNER:
            case 115:
                if (empty($pic)) throw new \Exception('图片必须上传');

                $id = $base['id'] ?? 0;
                $copy_id = $base['copy_id'] ?? 0;
                $img_size = $rules['img_size'] ?? 0;
                if (!(($id > 0 || $copy_id > 0) && $img_size == 0)) $this->rulesValid($rules, 0);
                break;
            case PositionModule::BOTTOM_NAV_TIPS:
                $index = $request->input('pos', '');
                PositionExtend::saveAppNavIcon($baseInfoId, $index);
                break;
            case PositionModule::SEARCH_RESULT_TOP_BANNER:
                $key_word = $request->input('key_word', '');
                PositionExtend::saveSearchResultBanner($baseInfoId, $key_word);
                break;
            case PositionModule::DESIGNER_HOME_BANNER:
                $uid = $request->input('uid', '');
                PositionExtend::saveDesignerHomeBanner($baseInfoId, $uid);
                break;
            case PositionModule::TBMINI_HOME_ACTIVITY:
                //左侧模块
                $l_bg_img= $request->input('l_bg_img', '');
                $l_rotation = $request->input('l_rotation', '0');
                $l_bg_img_link= $request->input('l_bg_img_link', '');
                //左侧模块-透出素材
                $l_imgs = $request->input('l_imgs', '');
                $l_img_links = $request->input('l_img_links', '');

                //右侧模块
                $r_bg_img= $request->input('r_bg_img', '');
                $r_rotation = $request->input('r_rotation', '0');
                $r_bg_img_link= $request->input('r_bg_img_link', '');
                //右侧模块-透出素材
                $r_imgs = $request->input('r_imgs', '');
                $r_img_links = $request->input('r_img_links', '');

                //处理左侧底图
                if(strpos($l_bg_img,'http') === false) {
                    $l_bg_img = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $l_bg_img ,
                        ImgUrl::IMAGE_SIZE_OP_ORI);
                }
                //处理右侧底图
                if(strpos($r_bg_img,'http') === false) {
                    $r_bg_img = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $r_bg_img ,
                        ImgUrl::IMAGE_SIZE_OP_ORI);
                }
                //处理左侧图片素材
                $l_imgs_res = [];
                if(empty($l_imgs)){
                    throw new \Exception('左侧模块-透出素材-图片，不可为空');
                }else{
                    $l_imgs_arr = explode(',',$l_imgs);
                    if(count($l_imgs_arr) %2 !=0){
                        throw new \Exception('左侧模块-透出素材-图片，图片数量必须为偶数');
                    }else{
                        if(count($l_imgs_arr) ==2) $l_rotation = 0; //如果只有两张素材 则不进行轮播
                        //处理左侧图片素材跳转链接
                        if($l_img_links){
                            $l_img_links = array_values(array_filter(array_column(FineGoodsService::arrayFilterFieldValue($l_img_links,
                                '_remove_',
                                0), 'l_img_links')));
                        }
                        if(count($l_imgs_arr) != count($l_img_links)){//判断左侧图片数量与跳转链接数量是否一致
                            throw new \Exception('左侧模块-透出素材，图片与跳转链接数量不符合');
                        }
                        foreach ($l_imgs_arr  as $value){
                            if(strpos($value,'http') === false) {
                                $l_imgs_res [] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $value ,
                                    ImgUrl::IMAGE_SIZE_OP_ORI);
                            }else{
                                $l_imgs_res[] = $value;
                            }
                        }
                        $l_imgs_res = implode(',',$l_imgs_res);
                    }
                }
                //处理右侧图片素材
                $r_imgs_res = [];
                if(empty($r_imgs)){
                    throw new \Exception('右侧模块-透出素材-图片，不可为空');
                }else{
                    $r_imgs_arr = explode(',',$r_imgs);
                    if(count($r_imgs_arr) %2 !=0){
                        throw new \Exception('右侧模块-透出素材-图片，图片数量必须为偶数');
                    }else{
                        if(count($r_imgs_arr) ==2) $r_rotation = 0; //如果只有两张素材 则不进行轮播
                        //处理右侧图片素材跳转链接
                        if($r_img_links){
                            $r_img_links = array_values(array_filter(array_column(FineGoodsService::arrayFilterFieldValue($r_img_links,
                                '_remove_',
                                0), 'r_img_links')));
                        }
                        if(count($r_imgs_arr) != count($r_img_links)){//判断右侧图片数量与跳转链接数量是否一致
                            throw new \Exception('右侧模块-透出素材，图片与跳转链接数量不符合');
                        }
                        foreach ($r_imgs_arr  as $value){
                            if(strpos($value,'http') === false) {
                                $r_imgs_res [] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $value ,
                                    ImgUrl::IMAGE_SIZE_OP_ORI);
                            }else{
                                $r_imgs_res[] = $value;
                            }
                        }
                        $r_imgs_res = implode(',',$r_imgs_res);
                    }
                }

                $dataJson = [
                    'l_bg_img'=>$l_bg_img, //左侧模块-底图图片
                    'l_rotation'=>$l_rotation,//是否轮播 1轮播 0 不轮播
                    'l_bg_img_link'=>$l_bg_img_link,//跳转链接
                    'l_imgs'=>$l_imgs_res,//左侧模块-透出素材-图片
                    'l_img_links'=>$l_img_links,//左侧模块-透出素材-跳转链接

                    'r_bg_img'=>$r_bg_img, //右侧模块-底图图片
                    'r_rotation'=>$r_rotation,//是否轮播 1轮播 0 不轮播
                    'r_bg_img_link'=>$r_bg_img_link,//跳转链接
                    'r_imgs'=>$r_imgs_res,//右侧模块-透出素材-图片
                    'r_img_links'=>$r_img_links,//右侧模块-透出素材-跳转链接
                ];

                PositionExtend::saveTbMiniHomeActivity($baseInfoId, json_encode($dataJson,true));
                break;
            default:
                break;
        }
    }

    public function beforeSortForm(Form $form)
    {
        switch ($this->positionId) {
            case PositionConstInterface::HOME_TOP_TRIFLE_BANNER:
            case 116:
            case 117:
                $this->gifControl($form);
                break;
        }
    }

    public function beforeLinkForm(Form $form)
    {
        switch ($this->positionId) {
            case PositionConstInterface::HOME_RANKING:
                $form->text('base.ext_type', '榜单id');
                $form->text('base.title', '运营文案');
                break;
            case PositionConstInterface::HOME_ROOF:
                $this->bannerFormWithCheck($form);
                $form->multiLinkSelect('base.link', '跳转链接', [LinkConf::LINK_H5_HTTPS, LinkConf::LINK_APP_FULLSCREEN]);
                break;
            case PositionConstInterface::HOME_TODAY_ARTICLE:
                $form->radio('base.ext_type', '类型')->options([0 => '今日整屋', 1 => '今日小事']);
                $form->text('base.title', '推荐标题');
                $this->bannerFormWithCheck($form);
                $form->multiLinkSelect('base.link', '跳转链接', [LinkConf::LINK_ARTICLE, LinkConf::LINK_H5_HTTPS, LinkConf::LINK_APP_FULLSCREEN]);
                break;
            case PositionConstInterface::TBMINI_HOME_ACTIVITY:
                $data = $form->data()['tbmini_text'] ?? '';
                if($data){ //判断是否是编辑状态
                    $data = json_decode($data,true);
                    $l_img_links = $data['l_img_links'];
                    $r_img_links = $data['r_img_links'];
                    if($l_img_links){
                        $data['l_img_links'] = [];
                        foreach ($l_img_links as $value){
                            $text['l_img_links'] = $value;
                            $data['l_img_links'][] = $text;
                        }
                    }
                    if($r_img_links){
                        $data['r_img_links'] = [];
                        foreach ($r_img_links as $value){
                            $text['r_img_links'] = $value;
                            $data['r_img_links'][] = $text;
                        }
                    }
                    $form->fill((array_merge($form->data(),$data)));
                }
                $form->divider('左侧模块');
                $form->imgUpload('l_bg_img', '底图图片', false, [
                    'isUpload' => true,
                    'isGetUrl' => false,
                    'imgType' => ImgUrl::APPTYPE_OP,
                    'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI,
                ])->help('底部图片请严格按照大促-一排二资源位规范上传');
                $form->radio('l_rotation','是否轮播')->options(['1' => '轮播', '0'=> '不轮播'])->default('1');
                $form->url('l_bg_img_link', '跳转链接')->required();
                $form->imgUpload('l_imgs', '透出素材-图片', true, [
                    'isUpload' => true,
                    'isGetUrl' => false,
                    'imgType' => ImgUrl::APPTYPE_OP,
                    'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI,
                ]);
                $form->table('l_img_links', '透出素材-跳转链接', function ($table) {
                    $table->text('l_img_links');
                })->required();

                $form->divider('右侧模块');
                $form->imgUpload('r_bg_img', '底图图片', false, [
                    'isUpload' => true,
                    'isGetUrl' => false,
                    'imgType' => ImgUrl::APPTYPE_OP,
                    'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI,
                ])->help('底部图片请严格按照大促-一排二资源位规范上传');
                $form->radio('r_rotation','是否轮播')->options(['1' => '轮播', '0'=> '不轮播'])->default('1');
                $form->url('r_bg_img_link', '跳转链接')->required();
                $form->imgUpload('r_imgs', '透出素材-图片', true, [
                    'isUpload' => true,
                    'isGetUrl' => false,
                    'imgType' => ImgUrl::APPTYPE_OP,
                    'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI,
                ]);
                $form->table('r_img_links', '透出素材-跳转链接', function ($table) {
                    $table->text('r_img_links');
                })->required();
                $form->confirm('确定更新吗？');
                break;
            default:
                $this->bannerFormWithCheck($form);
                break;
        }
    }

    public function beforeTitleForm(Form $form)
    {
        switch ($this->positionId) {
            case PositionConstInterface::NOTE_DETAIL_RECOMMEND_BANNER:
                $form->text('base.pos', '展示位置')
                    ->default(1)
                    ->required();
                break;
            case PositionConstInterface::BOTTOM_NAV_TIPS:
                $form->select('pos', '点击tab位置')
                    ->options(PositionModule::ADM_APP_TAB_MAP);
                $form->radio('base.pos', 'tab位置')
                    ->options(PositionModule::ADM_APP_TAB_MAP)
                    ->default(1)
                    ->required();
                break;
            case PositionConstInterface::SEARCH_RESULT_TOP_BANNER:
                $form->text('key_word', '搜索词')->required()->help('多个搜索词用,隔开');
                break;
            case PositionConstInterface::DESIGNER_HOME_BANNER:
                $form->text('uid', '设计师uid')->required()->help('多个设计师uid用,隔开');
                break;
            case PositionConstInterface::HOME_RECOMMEND_GREET_BANNER:
                $form->radio('base.close_type_show', '关闭时效')
                    ->options(PositionBaseInfo::CLOSE_TYPE_MAP)
                    ->disable()
                    ->help('4.15版本开始支持');
                $form->hidden('base.close_type', '关闭时效');
                break;
            default:
                break;
        }

    }

    public function defaultBaseInfo(Request $request): array
    {
        $response = parent::defaultBaseInfo($request);

        switch ($this->positionId) {
            case PositionConstInterface::HOME_RECOMMEND_GREET_BANNER:
                $response['close_type_show'] = PositionBaseInfo::CLOSE_TYPE_ONCE_INIT;
                $response['close_type'] = PositionBaseInfo::CLOSE_TYPE_ONCE_INIT;
                break;
            case PositionConstInterface::HOME_TODAY_ARTICLE:
                $response['link']['link_type'] = LinkConf::LINK_APP_FULLSCREEN;
                $response['link']['link_params']['url'] = "https://m.haohaozhu.cn/activity/operation/today-article/detail";
                break;

        }

        return $response;
    }

    public function extendDefaultBaseInfo()
    {
        $response = [];
        switch ($this->positionId) {
            case PositionConstInterface::SEARCH_RESULT_TOP_BANNER:
                $response = [
                    'key_word' => $this->relation['ad_unique'] ?? ''
                ];
                break;
        }
        return $response;
    }

    public function extendList(Grid $grid)
    {
        $img = true;
        switch ($this->positionId) {
            case PositionConstInterface::HOME_TOP_TRIFLE_BANNER:
            case 116:
            case 117:
                $img = false;
                $grid->column('pic_url', '图片')->image("", 120);
                $grid->column('play_times', '播放次数')->using(BaseModule::GIF_PLAY_TIMES);
                break;
            case PositionConstInterface::HOME_ROOF:
                $img = false;
                $grid->column('pic_url', '图片')->image("", 120);
                $grid->column('link', '链接地址')->width(250)->linkSelect(false, null, false);
                break;
            case PositionConstInterface::HOME_RANKING:
                $this->filter_field_pos = false;
                $this->filter_field_uid = false;
                $img = false;
                $grid->column('title', '运营文案');
                $grid->column('ext_type', '榜单id');
                break;
            case PositionConstInterface::HOME_TODAY_ARTICLE:
                $this->filter_field_pos = false;
                $this->filter_field_uid = false;
                $grid->column('title', '推荐标题');
                break;
            case PositionConstInterface::NOTE_DETAIL_RECOMMEND_BANNER:
                $grid->column('pos', '卡片位置');
                break;
            case PositionConstInterface::BOTTOM_NAV_TIPS:
                $grid->column('ext->pos', '点击tab位置')->using(PositionModule::ADM_APP_TAB_MAP);
                $grid->column('pos', 'tab位置')->using(PositionModule::ADM_APP_TAB_MAP);
                break;
            case PositionConstInterface::SEARCH_RESULT_TOP_BANNER:
                $grid->column('ext->key_word', '搜索词')->width(200)->label();
                break;
            case PositionConstInterface::DESIGNER_HOME_BANNER:
                $grid->column('ext->uid', '设计师uid')->label();
                break;
            case PositionConstInterface::TBMINI_HOME_ACTIVITY:
                $img = false;
                $grid->column('l_bg_img', '左侧图片')->display(function (){
                    $data = ($this->ext)['tbmini_text'] ?? '';
                    if($data){
                        $dataMap = json_decode($data,true);
                        $imgPath = $dataMap['l_bg_img'];
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:150px;height:150px;' class='img img-thumbnail' />" : "";
                        $html = '';
                        if ($image) {
                            $html .= '<a href="javascript:layer.open({type: 2,shadeClose: true,title: \'预览\',maxmin: true,area: [\'800px\', \'600px\'],content: \'' . $imgPath . '\'});">';
                            $html .= $image;
                            $html .= '</a>';
                        }
                        return $html;
                    }
                })->width(200);
                $grid->column('l_bg_img_link', '一级链接')->display(function (){
                    $data = ($this->ext)['tbmini_text'] ?? '';
                    if($data){
                        $dataMap = json_decode($data,true);
                        return $dataMap['l_bg_img_link'];
                    }
                })->copyable()->width(200);
                $grid->column('r_bg_img', '右侧图片')->display(function (){
                    $data = ($this->ext)['tbmini_text'] ?? '';
                    if($data){
                        $dataMap = json_decode($data,true);
                        $imgPath = $dataMap['r_bg_img'];
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:150px;height:150px;' class='img img-thumbnail' />" : "";
                        $html = '';
                        if ($image) {
                            $html .= '<a href="javascript:layer.open({type: 2,shadeClose: true,title: \'预览\',maxmin: true,area: [\'800px\', \'600px\'],content: \'' . $imgPath . '\'});">';
                            $html .= $image;
                            $html .= '</a>';
                        }
                        return $html;
                    }
                })->width(200);
                $grid->column('r_bg_img_link', '一级链接')->display(function (){
                    $data = ($this->ext)['tbmini_text'] ?? '';
                    if($data){
                        $dataMap = json_decode($data,true);
                        return $dataMap['r_bg_img_link'];
                    }
                })->copyable()->width(200);
                break;
            default:
                break;
        }
        if ($img) $grid->column('pic_url', '图片')->image("", 120);
    }

    public function beforeTab(Tab $tab)
    {
        if (PositionConstInterface::BOTTOM_NAV_TIPS == $this->positionId) {
            $tab->addLink('icon列表', '/admin/app/bottomNav/index', false);
            $tab->addLink('链接配置', '/admin/app/bottomNavConf/index', false);
        }
    }

    public function afterTab(Tab $tab, Request $request)
    {
        if (PositionConstInterface::TAB_NAV_BG == $this->positionId) {
            $this->tabName = "「底导航背景」列表";
            $tab->addLink('「发布按钮」列表', '/admin/position/singleBanner/113', false);
        }
        if (113 == $this->positionId) {
            $this->tabName = "「发布按钮」列表";
            $tab->addLink('「底导航背景」列表', '/admin/position/singleBanner/112', false);
        }
    }

    public function init()
    {
        switch ($this->positionId) {
            case PositionConstInterface::BOTTOM_NAV_TIPS:
                $this->tabName = '气泡配置';
                break;
            case PositionConstInterface::HOME_TODAY_ARTICLE:
                $this->filter_field_pos = false;
                $this->filter_field_uid = false;
                break;
        }
    }
}
